from channels.generic.websocket import WebsocketConsumer
from django.http.request import QueryDict
import json
import base64
import paramiko


class WebSSH(WebsocketConsumer):
    message = {'status': 0, 'message': None}
    """
    status:
        0: ssh 连接正常, websocket 正常
        1: 发生未知错误, 关闭 ssh 和 websocket 连接

    message:
        status 为 1 时, message 为具体的错误信息
        status 为 0 时, message 为 ssh 返回的数据, 前端页面将获取 ssh 返回的数据并写入终端页面
    """

    def connect(self):
        """
        打开 websocket 连接, 通过前端传入的参数尝试连接 ssh 主机
        :return:
        """
        self.accept()
        query_string = self.scope.get('query_string')
        ssh_args = QueryDict(query_string=query_string, encoding='GB2312')

        width = ssh_args.get('width')
        height = ssh_args.get('height')
        port = ssh_args.get('port')

        width = int(width)
        height = int(height)
        port = int(port)

        auth = ssh_args.get('auth')
        ssh_key_name = ssh_args.get('ssh_key')
        passwd = ssh_args.get('password')

        host = ssh_args.get('host')
        user = ssh_args.get('user')

        if passwd:
            passwd = base64.b64decode(passwd).decode('GB2312')
        else:
            passwd = None

        print (host,user,passwd)

        # self.ssh = SSH(websocker=self, message=self.message)
        self.ssh = paramiko.SSHClient()  # 1 创建SSH对象
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # self.ssh.connect("172.25.1.189", username="admin", password="2018.pw.")

        ssh_dict = {
            'host': host,
            'user': user,
            'port': port,
            'timeout': 30,
            'pty_width': width,
            'pty_height': height,
            'password': passwd
        }

        # self.ssh.connect(**ssh_dict)
        a = self.ssh.connect(host, username=user,password=passwd)
        # stdin, stdout, stderr = self.ssh.exec_command('dir')
        print("连接成功: {}".format (a))

    def disconnect(self, close_code):
        try:
            self.ssh.close()
        except:
            pass

    def receive(self, text_data=None, bytes_data=None):
        data = json.loads(text_data)
        print (data)
        if type(data) == dict:
            status = data['status']
            if status == 0:
                data = data['data']
                print (data)
                stdin, stdout, stderr = self.ssh.exec_command(data)

                right_info = stdout.read()
                err_info = stderr.read()
                print(right_info)

                if right_info:
                    new_data = right_info.decode("GB2312")
                    print(new_data)
                    self.send(new_data)
                elif err_info:
                    new_data = err_info.decode("GB2312")
                    print(new_data)
                    self.send(new_data)
                # self.ssh.shell(data)
            else:
                cols = data['cols']
                rows = data['rows']
                print (cols,rows)
                # self.ssh.resize_pty(cols=cols, rows=rows)